import logging
from .cm_user import CmUser
from init import db
from typing import Optional

logger = logging.getLogger(__name__)

USER_TOKEN_CACHE = {}

def register_user(source: int, source_id: str):
    ds  = db.session
    user = CmUser(source=source, source_id=source_id)
    ds.add(user)
    ds.commit()
    ds.refresh(user)
    return user

def get_user_by_source_id(source_id: str, source: int) -> Optional[int]:
    user_id = USER_TOKEN_CACHE.get(source_id)
    if user_id is None:
        ds  = db.session
        user = ds.query(CmUser).filter(CmUser.source == source, CmUser.source_id == source_id).first()
        if user is None:
            logger.info(f"user not found, register source_id: {source_id}, source: {source}")
            #user = register_user(source, source_id)
            return None
        USER_TOKEN_CACHE[source_id] = user.id
        user_id = USER_TOKEN_CACHE.get(source_id)
    return user_id




